<?php


namespace App\Models;


use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasDateTimeFormatter;
    protected $table = 'categorys';


    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    // 定义与子分类的关联
    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    // 递归生成带缩进的树形选项
    public static function treeOptions($parentId = 0, $prefix = '')
    {
        $options = [];
        $categories = self::where('parent_id', $parentId)->get();

        foreach ($categories as $category) {
            // 生成缩进前缀（使用空格或符号表示层级）
            $indent = str_repeat('　', 2) . $prefix;
            $options[$category->id] = "{$indent}{$category->name}";

            // 递归获取子分类
            $children = self::treeOptions($category->id, $prefix . '— ');
            $options = array_merge($options, $children);
        }

        return $options;
    }
}
